package com.atguigu.app.func;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.Constant;
import com.atguigu.utils.HBaseUtil;
import com.atguigu.utils.JedisUtil;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.apache.hadoop.hbase.client.Connection;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class DimInfoFunction {

    public static JSONObject getDimInfo(Jedis jedis, Connection connection, String tableName, String key) throws IOException {

        //查询Redis
        String redisKey = "DIM:" + tableName + ":" + key;
        System.out.println("redisKey:" + redisKey);
        String dimInfoJsonStr = jedis.get(redisKey);
        if (dimInfoJsonStr != null) {
            jedis.expire(redisKey, Constant.ONE_DAY);
            return JSONObject.parseObject(dimInfoJsonStr);
        }

        //没有在Redis查到数据,则查询HBase
        JSONObject jsonObject = HBaseUtil.getData(connection, tableName, key);

        //将数据写入Redis
        jedis.setex(redisKey, Constant.ONE_DAY, jsonObject.toJSONString());

        //返回结果
        return jsonObject;
    }

    //使用异步客户端从Redis读取数据
    public static JSONObject getRedisDimInfo(StatefulRedisConnection<String, String> redisConnection, String tableName, String key) throws ExecutionException, InterruptedException {
        String redisKey = "DIM:" + tableName + ":" + key;
        String dimInfoStr = redisConnection.async().get(redisKey).get();
        if (dimInfoStr != null) {
            redisConnection.async().expire(redisKey, Constant.ONE_DAY);
        }
        return JSON.parseObject(dimInfoStr);
    }

    public static void setRedisDimInfo(StatefulRedisConnection<String, String> redisConnection, String tableName, String key, String dimInfoStr) {
        RedisAsyncCommands<String, String> async = redisConnection.async();
        String redisKey = "DIM:" + tableName + ":" + key;
        async.setex(redisKey, Constant.ONE_DAY, dimInfoStr);
    }

    public static void main(String[] args) throws IOException {
        Connection connection = HBaseUtil.getConnection();
        Jedis jedis = JedisUtil.getJedis();

        long start = System.currentTimeMillis();
        System.out.println(getDimInfo(jedis, connection, "dim_base_category1", "20"));
        long end = System.currentTimeMillis();
        System.out.println(getDimInfo(jedis, connection, "dim_base_category1", "20"));
        long end2 = System.currentTimeMillis();

        System.out.println(end - start);
        System.out.println(end2 - end);

        connection.close();
    }
}
